package com.ran.java_gobang_new.api;

import com.ran.java_gobang_new.manager.OnlineManager;
import com.ran.java_gobang_new.pojo.dao.UserInfo;
import com.ran.java_gobang_new.pojo.request.MatchRequest;
import com.ran.java_gobang_new.pojo.response.Result;
import com.ran.java_gobang_new.pojo.response.UserInfoGameHallReponse;
import com.ran.java_gobang_new.service.MatchService;
import com.ran.java_gobang_new.utils.BeanTrans;
import com.ran.java_gobang_new.utils.JsonTrans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-09-03
 * Time: 12:54
 */
@Component
@Slf4j
public class MarchAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineManager onlineManager;

    @Autowired
    private MatchService matchService;
    // 连接建立后
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 1. 确定谁在游戏大厅建立的连接
        // 2. 如果是直接跳到大厅的用户拦截, 要跳转到登录
        // 3. 如果该用户是正常登录的, 要加入到在线 onlinemap 中
        // 4. 处理双开
        UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
        WebSocketSession hallSession = onlineManager.getHallSession(userInfo.getUserId());
        WebSocketSession roomSession = onlineManager.getRoomSession(userInfo.getUserId());
        if (userInfo == null) {
            log.error("用户未登录非法进入游戏大厅");
            session.sendMessage(JsonTrans.trans(Result.fail("您当前未登录,无法匹配!")));
            return;
        }
        if (hallSession != null || roomSession != null) {
            log.error("用户: " + userInfo.getUserName() + " 多开!");
            session.sendMessage(JsonTrans.trans(Result.fail("检测到您当前可能多开, 即将断开连接!")));
            return;
        }
        if (userInfo != null  && userInfo.getUserId() > 0 && hallSession == null && session != null) {
            log.info("玩家: " +userInfo.getUserName() + " 已上线!");
            onlineManager.addHall(userInfo.getUserId(),session);
            return;
        }
        session.sendMessage(JsonTrans.trans(Result.fail("获取用户信息异常!")));
    }

    // 信息传输时
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
      /* 1. startMatch 开始匹配
       2. stopMatch 停止匹配
       3.  success 匹配成功*/
        // 先获取 前端发过来的信息, 判断到底是什么信息
        UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
        MatchRequest trans = JsonTrans.trans(message);
        UserInfoGameHallReponse userInfoGameHallReponse = BeanTrans.trans(userInfo);

        if (trans.getMessage().equals("startMatch")) {
            // 正在匹配, 该怎么处理匹配信息
            // 查看点击匹配的用户 id 是否和 建立的连接用户 id 一致
            // 加入匹配队列
            log.info("用户: " + userInfoGameHallReponse.getUserName() + " 开始匹配");
            matchService.add(userInfoGameHallReponse);
            session.sendMessage(JsonTrans.trans(Result.success("startMatch")));
        }else if (trans.getMessage().equals("stopMatch")) {
            log.info("用户: " + userInfoGameHallReponse.getUserName() + " 结束匹配");
            // 从匹配队列删除
            matchService.remove(userInfoGameHallReponse);
            // 返回停止匹配的 信息
            session.sendMessage(JsonTrans.trans(Result.success("stopMatch")));
        }else {
            matchService.remove(userInfoGameHallReponse);
            log.error("前端传来的错误信息!");
            session.sendMessage(JsonTrans.trans(Result.success("错误信息")));
        }

    }

    // 连接异常关闭
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 连接异常关闭返回匹配失败, 下线
        UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
        if (userInfo == null) {
            log.error("匹配连接异常!");
            session.sendMessage(JsonTrans.trans(Result.fail("您未登录, 不能匹配!")));
            throw new NullPointerException("您当前未登录!");
        }
        UserInfoGameHallReponse userInfoGameHallReponse = BeanTrans.trans(userInfo);
        WebSocketSession hallSession = onlineManager.getHallSession(userInfo.getUserId());
        log.info("用户: " + userInfoGameHallReponse.getUserName() + " 异常下线");
        if (session == hallSession) {
            onlineManager.removeHall(userInfo.getUserId());
            matchService.remove(userInfoGameHallReponse);
        }
    }

    // 连接关闭后
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接正常关闭返回匹配失败, 下线
        UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
        if (userInfo == null) {
            log.error("匹配连接关闭!");
            session.sendMessage(JsonTrans.trans(Result.fail("您未登录, 不能匹配!")));
            throw new NullPointerException("您当前未登录!");
        }
        UserInfoGameHallReponse userInfoGameHallReponse = BeanTrans.trans(userInfo);
        WebSocketSession hallSession = onlineManager.getHallSession(userInfo.getUserId());
        log.info("用户: " + userInfoGameHallReponse.getUserName() + " 正常下线");
        // 正常下线
        if (session == hallSession) {
            onlineManager.removeHall(userInfo.getUserId());
            matchService.remove(userInfoGameHallReponse);
        }
    }
}
